<template>
  <view class="container">
    <u-form :model="form" ref="uForm" :rules="rules" label-width="80">
      <u-form-item label="姓名" prop="name" required>
        <u-input v-model="form.name" placeholder="请输入姓名" />
      </u-form-item>
      <u-form-item label="手机号" prop="phone" required>
        <u-input v-model="form.phone" placeholder="请输入手机号" type="number" maxlength="11" />
      </u-form-item>
      <u-form-item label="办理业务" prop="type" required>
		<uni-data-checkbox v-model="form.type" :localdata="typeOptions"></uni-data-checkbox>
      </u-form-item>
      <u-form-item label="客户状态" prop="status" required>
          <uni-data-checkbox 
		  :multiple="false"
		  v-model="form.status"
		  :localdata="statusOptions"
          ></uni-data-checkbox>
      </u-form-item>
	  <u-form-item label="关联人" prop="associated_users" required>
	  	<uni-data-select v-model="form.associated_users" :localdata="userOptions"></uni-data-select>
	  </u-form-item>
      <u-form-item label="客户来源" prop="source">
        <uni-data-select v-model="form.source" :localdata="sourceOptions"></uni-data-select>
      </u-form-item>
     <!-- <u-form-item label="身份证号" prop="id_card">
        <u-input v-model="form.id_card" placeholder="请输入身份证号" />
      </u-form-item>
	  <u-form-item label="负债情况" prop="debt_info" required>
	      <uni-data-checkbox 
	  		  :multiple="false"
	  		  v-model="form.debt_info"
	  		  :localdata="debtStatusOptions"
	      ></uni-data-checkbox>
	  </u-form-item>
      <u-form-item label="还款日">
        <uni-datetime-picker
          v-model="form.repayment_date" 
          :show="showDatePicker"
          type="date"
          @change="dateConfirm"
          @cancel="showDatePicker = false"
        ></uni-datetime-picker>
      </u-form-item>
      <u-form-item label="生日">
        <uni-datetime-picker 
          v-model="form.birthday" 
          :show="showBirthdayPicker"
          type="date"
          @change="birthdayConfirm"
          @cancel="showBirthdayPicker = false"
        ></uni-datetime-picker>
      </u-form-item> -->
     <!-- <uni-forms-item name="spouse" label="配偶信息">
       <uni-easyinput v-model="form.spouse"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="company_info" label="企业信息">
        <uni-easyinput v-model="form.company_info"></uni-easyinput>
      </uni-forms-item> -->
      <u-button type="primary" @click="submit">保存</u-button>
    </u-form>
  </view>
</template>

<script>
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	const Odb=uniCloud.importObject('mydb-customer')
	let eventChannel=null
export default {
  data() {
    return {
      customerId: null,
      form: {
        name: '',
        phone: '',
        type: 'credit',
        status: 'potential',
        source: 'online',
		debt_info:"无负债",
        id_card: '',
        spouse: '',
        repayment_date: null,
        birthday: null,
        associated_users: null,
        company_info: '',
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
        ],
        type: [{ required: true, message: '请选择业务类型', trigger: 'change' }],
        status: [{ required: true, message: '请选择客户状态', trigger: 'change' }],
        associated_users: [{ required: true, message: '请选择关联人员', trigger: 'change' }]
      },
      typeOptions: [],
      statusOptions: [],
      sourceOptions: [],
	  debtStatusOptions: [],
      userOptions: [],
      showSourcePicker: false,
      showUserPicker: false,
      showDatePicker: false,
      showBirthdayPicker: false,
      showCompanyForm: false,
      showSpouseForm: false
    }
  },
  computed: {
	  userInfo() {
		return store.userInfo
	  },
    repaymentDateText() {
      return this.form.repayment_date ? this.$u.timeFormat(this.form.repayment_date, 'yyyy-mm-dd') : ''
    },
    birthdayText() {
      return this.form.birthday ? this.$u.timeFormat(this.form.birthday, 'yyyy-mm-dd') : ''
    }
  },
  onLoad(options) {
	eventChannel = this.getOpenerEventChannel();
    if (options.id) {
      this.customerId = options.id
      this.loadCustomerData()
    }
	this.loadOptions()
    this.loadUserOptions()
  },
  methods: {
    dateConfirm(e) {
      this.form.repayment_date = e.value
      this.showDatePicker = false
    },
    
    birthdayConfirm(e) {
      this.form.birthday = e.value
      this.showBirthdayPicker = false
    },
    loadOptions(){
		Odb.getOptions().then((res)=>{
			for (var key in res) {
				if (res.hasOwnProperty(key) && this[key]) {
					this[key] = res[key]
				}
			}
		})
	},
    async loadCustomerData() {
      const db = uniCloud.database()
      const res = await db.collection('mydb-customer').doc(this.customerId).get()
      if (res.result.data.length > 0) {
        this.form = res.result.data[0]
      }
    },
    
    async loadUserOptions() {
      const db = uniCloud.database()
      const res = await db.collection('uni-id-users').field("nickname,_id").get()
      // 查询关联人员
      const users = res.result.data.map(user => {
        return {
          text: user.nickname,
          value: user._id
        }
      })
      this.form.associated_users=this.userInfo._id
      this.userOptions = users
    },
    
    async submit() {
		this.$refs.uForm.validate().then(res => {
          this.saveCustomer()
      })
    },
    
    async saveCustomer() {
      const db = uniCloud.database()
      
      // 添加当前用户信息
      const data = {
        ...this.form,
        update_date: Date.now()
      }
      
      if (!this.customerId) {
        // 新增
        data.create_date = Date.now()
        data.creator_id = this.userInfo._id
        await db.collection('mydb-customer').add(data)
        uni.showToast({ title: '创建成功' })
      } else {
        delete data._id
        await db.collection('mydb-customer').doc(this.customerId).update(data)
        uni.showToast({ title: '更新成功' })
      }
      
      setTimeout(() => {
		  uni.navigateBack()
		  eventChannel.emit('refresh',null);
	  }, 1500)
    }
  }
}
</script>

<style scoped>
.popup-content {
  padding: 30rpx;
}

.spouse-info {
  background-color: #f9f9f9;
  padding: 20rpx;
  border-radius: 10rpx;
  margin-bottom: 30rpx;
}
</style>